<?php
/**
 * User.php
 *
 * @author: antonio ramirez <antonio@clevertech.biz>
 * Date: 7/22/12
 * Time: 11:42 PM
 */
/**
 * This is the model class for table "{{user}}".
 *
 * The followings are the available columns in table '{{user}}':
 * 
 * @property integer $id
 * @property string $username
 * @property string $email
 * @property string $password
 * @property string $active_key
 * @property integer $login_attempts
 * @property integer $createtime
 * @property integer $updatetime
 * @property integer $lastvisit
 * @property integer $superuser
 * @property integer $status
 * @property integer $place_id
 * @property integer $partner_id
 */
class User extends CActiveRecord
{    
	const STATUS_NOACTIVE = 0;
	const STATUS_ACTIVE = 1;
	const STATUS_BANED = -1;
    
    const IS_SUPERUSER = 1;
    const NOT_SUPERUSER = 0;
    
	/**
	 * Returns the static model of the specified AR class.
	 * @return Customer the static model class
	 */
	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'user';
	}

	/**
	 * Behaviors
	 * @return array
	 */
	/*
	public function behaviors()
	{
		Yii::import('common.extensions.behaviors.password.*');
		return array(
			// Password behavior strategy
			"APasswordBehavior" => array(
				"class" => "APasswordBehavior",
				"defaultStrategyName" => "legalcyMd5",
				"strategies" => array(
					"bcrypt" => array(
						"class" => "ABcryptPasswordStrategy",
						"workFactor" => 14,
						"minLength" => 8
					),
					"legacyMd5" => array(
						"class" => "ALegacyMd5PasswordStrategy",
						'minLength' => 8
					),                    
					"legacySha1" => array(
						"class" => "ALegacySha1PasswordStrategy",
						'minLength' => 8
					)
				),
			)
		);
	}
	*/

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('username, email, superuser, status', 'required'),
            array('active_key, password', 'required', 'on'=>'register'),
			array('email', 'unique', 'message' => Yii::t('validation', 'Email has already been taken.')),
            array('username', 'unique', 'message' => Yii::t('validation', 'Username has already been taken.')),
			array('email', 'email'),
			array('email, password, active_key', 'length', 'max' => 255),
            array('username', 'match', 'pattern' => '/^[A-Za-z0-9_]+$/u','message' => Yii::t('message',"Incorrect symbols (A-z0-9).")),
			array('status', 'in', 'range'=>array(self::STATUS_NOACTIVE,self::STATUS_ACTIVE,self::STATUS_BANED)),
			array('superuser', 'in', 'range'=>array(0,1)),
			array('login_attempts, createtime, updatetime, lastvisit, superuser, status, place_id, partner_id', 'numerical', 'integerOnly' => true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, username, email, password, superuser, status, place_id, partner_id', 'safe', 'on' => 'search'),
		);
	}
    
    public function relations()
    {
        return array(
			'profile'=>array(self::HAS_ONE, 'Profile', 'user_id'),
			'default_place'=>array(self::HAS_ONE, 'Place', array('id'=>'place_id')),
			'places'=>array(self::HAS_MANY, 'Place','user_id'),
			'partner'=>array(self::BELONGS_TO, 'Partner', 'partner_id')
		);
    }

	/**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => Yii::t('label','ID'),
            'username' => Yii::t('label','Tên đăng nhập'),
            'email' => Yii::t('label','Email'),
            'password' => Yii::t('label','Mật khẩu'),
            'active_key' => Yii::t('label','Active Key'),
            'login_attempts' => Yii::t('label','Login Attempts'),
            'createtime' => Yii::t('label','Ngày đăng ký'),
            'updatetime' => Yii::t('label','Ngày chỉnh sửa'),
            'lastvisit' => Yii::t('label','Lần đăng nhập cuối'),
            'superuser' => Yii::t('label','Superuser'),
            'status' => Yii::t('label','Trạng thái'),
            'place_id'=>Yii::t('label','Địa chỉ'),
            'partner_id'=>Yii::t('label','Công ty'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('active_key',$this->active_key,true);
        $criteria->compare('login_attempts',$this->login_attempts);
        $criteria->compare('createtime',$this->createtime);
        $criteria->compare('updatetime',$this->updatetime);
        $criteria->compare('lastvisit',$this->lastvisit);
        $criteria->compare('superuser',$this->superuser);
        $criteria->compare('status',$this->status);
        $criteria->compare('place_id',$this->place_id);
        $criteria->compare('partner_id',$this->partner_id);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }

	/**
	 * Helper property function
	 * @return string the full name of the customer
	 */
	public function getFullName()
	{
		$profile = $this->profile;
        if($profile && $profile->firstname && $profile->lastname)
            return $profile->firstname . ' ' . $profile->lastname;
        else return $this->username;
	}
	
	/**
	 * Get address of this user
	 * @return string the address (address district_name, province_name)
	 */
 	public function getAddress()
 	{
 		$place = $this->default_place;
 		if($place) {
 			return $place->address;// . ', ' . $place->district->name . ', ' . $place->district->province->name;
 		}
 		else return null;
 	}

	/**
	 * Makes sure usernames are lowercase
	 * (emails by standard can have uppercase letters)
	 * @return parent::beforeValidate
	 */
	public function beforeValidate()
	{
		if (!empty($this->username))
			$this->username = strtolower($this->username);
		return parent::beforeValidate();
	}
    
    public function beforeSave()
    {
        if(parent::beforeSave()) {
            if($this->isNewRecord)
                $this->createtime = time();
            else
                $this->updatetime = time();
            return true;
        }
        return false;
    }
    
    public function getAvatar()
    {
        if($this->profile && $this->profile->picture)
            return $this->profile->picture;
        else return '/images/avatar/no-avatar.gif';
    }

	/**
	 * Generates a new validation key (additional security for cookie)
	 */
	public function regenerateValidationKey()
	{
		$this->saveAttributes(array(
			'active_key' => Yii::app()->usercomponent->encrypting(mt_rand() . mt_rand() . mt_rand()),
		));
	}

}